package com.bookbuf.social.share.content.media.image.converter;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.bookbuf.social.secure.AesHelper;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by robert on 16/7/4.
 */
public class BinaryConverter extends ConfiguredConverter {

	private byte[] binaryDrawable;

	public BinaryConverter (byte[] binaryDrawable) {
		this.binaryDrawable = binaryDrawable;
	}

	public String getFileName () {
		return AesHelper.md5 (String.valueOf (System.currentTimeMillis ()));
	}

	private File writeFile (byte[] binaryDrawable, File file) {
		BufferedOutputStream outputStream = null;
		try {
			FileOutputStream fileOutputStream = new FileOutputStream (file);
			outputStream = new BufferedOutputStream (fileOutputStream);
			outputStream.write (binaryDrawable);
		} catch (Exception e) {
			e.printStackTrace ();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close ();
				} catch (IOException e) {
					e.printStackTrace ();
				}
			}

		}

		return file;
	}

	@Override
	public File asFile () {

		File file = null;
		try {
			file = this.getConfig ().generateCacheFile (this.getFileName ());
			return this.writeFile (this.binaryDrawable, file);
		} catch (IOException e) {
			e.printStackTrace ();
		}
		return file;
	}

	@Override
	public String asUrl () {
		return null;
	}

	@Override
	public byte[] asBinary () {
		return this.binaryDrawable;
	}

	@Override
	public Bitmap asBitmap () {
		return this.binaryDrawable != null ? BitmapFactory.decodeByteArray (this.binaryDrawable, 0, this.binaryDrawable.length) : null;
	}
}